package org.eclipse.wtp.sample.flashcards;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// read data from form
		String answer = request.getParameter("button1"); 
		
		// get reference to FlashCardHand
		FlashCardHand localHand = (FlashCardHand)request.getSession().getAttribute("flashcardhand");
		
		// initialize result text
		String result = "";
		
		// determine whether answer is correct
		boolean correct = localHand.isCorrect(answer);
		if (correct) {
			// add one to 'correct' score
			Integer oldscore = (Integer)request.getSession().getAttribute("correct");
			request.getSession().setAttribute("correct", new Integer(oldscore.intValue() + 1));
			result = "Correct!";
		}
		else {
			// add one to 'incorrect' score
			Integer oldscore = (Integer)request.getSession().getAttribute("incorrect");
			request.getSession().setAttribute("incorrect", new Integer(oldscore.intValue() + 1));
			result = "Incorrect.";
		}
		
		// generate result message
		result = result + " " + localHand.getTestKey1() + " matches " + localHand.getTestKey2(); 
		
		// draw new set of cards
		localHand.draw();
		
		// for testing only
		String context = getServletContext().getRealPath("/");
		request.setAttribute("context", context);
		//String setName = request.getParameter("set");
		//String userName = request.getParameter("user");
		
		// create and initialize FlashCardSet and User
		//FlashCardSet flashcardset = new FlashCardSet(setName);
		//User user = new User(userName);

		// save FlashCardSet to Session
		//request.getSession().setAttribute("flashcardset", flashcardset);
		//request.getSession().setAttribute("user", user);
		
		//request.setAttribute("localuser", user);
		//request.setAttribute("localset", flashcardset);
		request.setAttribute("result", result );

		getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

	}

}